package cn.mes.module.mes.utils.kingdee;


import cn.hutool.core.map.MapBuilder;
import cn.mes.module.mes.controller.admin.baseworkplan.vo.BaseWorkPlanSynchronizationVO;
import cn.mes.module.mes.dal.dataobject.baseworkplan.BaseBomChildDO;
import cn.mes.module.mes.dal.dataobject.baseworkplan.BaseWorkPlanDO;
import cn.mes.module.mes.enums.DefaultEnum;
import cn.mes.module.mes.enums.ExchangeTypeEnum;
import cn.mes.module.mes.enums.WorkShopEnum;
import cn.mes.module.mes.service.baseworkplan.BaseWorkPlanService;
import cn.mes.module.mes.utils.kingdee.bom.Bom;
import cn.mes.module.mes.utils.kingdee.bom.Page2;
import cn.mes.module.mes.utils.kingdee.workplan.Data;
import cn.mes.module.mes.utils.kingdee.workplan.Page1;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Title: <br>
 * Description: <br>
 * Copyright: Copyright (c) 2024<br>
 * Company: 四川瀚海精密制造有限公司<br>
 *
 * @author youchuang
 * @version 1.0
 * @date 2024-08-28 15:07
 */
@Component
@Log4j2
public class KingDeeGetDataUtils {
    @Value("${kingdee.baseInfo.authorityCode}")
    private String kingdeeAuthorityCode;


    @Value("${kingdee.baseInfo.baseUrl}")
    private String kingdeeBaseUrl;

    @Value("${kingdee.baseInfo.url.createToken}")
    private String createTokenUrl;

    @Value("${kingdee.baseInfo.url.getWorkPlanList}")
    private String getWorkPlanListUrl;

    @Value("${kingdee.baseInfo.url.getWorkPlanDetail}")
    private String getWorkPlanDetailUrl;

    @Value("${kingdee.baseInfo.url.getBomList}")
    private String getBomList;

    @Value("${kingdee.baseInfo.url.getBomDetail}")
    private String getBomDetail;

    @Value("${kingdee.baseInfo.fmanagerid}")
    private String kingdeeFManagerId;


    @Value("${kingdee.baseInfo.smanagerid}")
    private String kingdeeSManagerId;

    @Resource
    private BaseWorkPlanService baseWorkPlanService;

    public String getKingdeeToken() {
        String url = kingdeeBaseUrl + createTokenUrl + kingdeeAuthorityCode;
        HttpHeaders headers = new HttpHeaders();
        RestTemplate restTemplate = new RestTemplate();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        Map<Object, Object> map = new HashMap<>();
        HttpEntity<Map<Object, Object>> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        JSONObject jsonObject = JSON.parseObject(responseEntity.getBody());
        TokenModel tokenModel = jsonObject.getObject("Data", TokenModel.class);
        return tokenModel.getToken();
    }

//    @Scheduled(fixedDelay = 600000)
    public void getData() throws IOException {
//        getWorkPlanInfo(BaseWorkPlanSynchronizationVO.builder().size(500).bom(true).build());
        getBomChildInfo(BaseWorkPlanSynchronizationVO.builder().size(500).bom(true).build());
    }

    public void getWorkPlanInfo(BaseWorkPlanSynchronizationVO baseWorkPlanSynchronizationVO) throws IOException {
        String token = getKingdeeToken();
        String url = kingdeeBaseUrl + getWorkPlanListUrl + token;
        log.info("URL:{}", url);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        if(StringUtils.isBlank(baseWorkPlanSynchronizationVO.getBillno())) {

            Map<Object, Object> dataMap = MapBuilder.create()
                    .put("Top", baseWorkPlanSynchronizationVO.getSize())
                    .put("PageSize", baseWorkPlanSynchronizationVO.getSize())
                    .put("PageIndex", "1")
                    .put("OrderBy", "[FBillNo] DESC")
                    .put("SelectPage", "1").build();
            if (baseWorkPlanSynchronizationVO.getStatus() != null) {
                dataMap.put("Filter", "[FStatus] =" + baseWorkPlanSynchronizationVO.getStatus());
                //                        .put("Filter","[FStatus] =1")
            }
            Map<Object, Object> map = MapBuilder.create().put("Data", dataMap).build();
            HttpEntity<Map<Object, Object>> httpEntity = new HttpEntity<>(map, headers);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
            log.error("D:{}", responseEntity.getBody());
            JSONObject jsonObject = JSON.parseObject(responseEntity.getBody());
            if (jsonObject.getIntValue("StatusCode") == 200) {
                JSONObject Data = jsonObject.getJSONObject("Data");
                JSONArray jsonArray = Data.getJSONArray("DATA");
                List<BaseWorkPlanDO> workPlanDOList = Lists.newArrayList();
                for (Object object : jsonArray) {
                    String billNo = JSONObject.parseObject(JSONObject.toJSONString(object)).getString("FBillNo");
                    BaseWorkPlanDO baseWorkPlanDO = getPDDetail(billNo);
                    workPlanDOList.add(baseWorkPlanDO);
                }
                if (CollectionUtils.isNotEmpty(workPlanDOList)) {
                    baseWorkPlanService.createBaseWorkPlanBatch(workPlanDOList);
                }
            }
        }else{
            String billNo = baseWorkPlanSynchronizationVO.getBillno();
            BaseWorkPlanDO baseWorkPlanDO = getPDDetail(billNo);
            if(baseWorkPlanDO!=null){
                baseWorkPlanService.createBaseWorkPlan(baseWorkPlanDO);
            }
        }


    }

    public BaseWorkPlanDO getPDDetail(String billNo) throws IOException {
        String token = this.getKingdeeToken();
        String url = kingdeeBaseUrl + getWorkPlanDetailUrl + token;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        Map<Object, Object> map = MapBuilder.create().put("Data",
                MapBuilder.create().put("FBillNo", billNo).build()).build();
        HttpEntity<Map<Object, Object>> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(responseEntity));
        JSONObject body = jsonObject.getJSONObject("body");
        Data data = body.getObject("Data", Data.class);
        log.error("Data:{}",JSONObject.toJSONString(data));
        Page1 page = data.getPage1().get(0);

        BaseWorkPlanDO sysWorkPlan = new BaseWorkPlanDO();
        /*工单编号*/
        sysWorkPlan.setId(page.getFBillNo());
        sysWorkPlan.setWorkPlanId(page.getFBillNo());
        /*产品名称*/
        sysWorkPlan.setProductName(page.getFItemName());
        /*产品料号*/
        sysWorkPlan.setProductId(page.getFItemID().getFNumber());
        /*计划开始时间*/
        sysWorkPlan.setPlanStartTime(page.getFPlanCommitDate());
        /*计划结束时间*/
        sysWorkPlan.setPlanEndTime(page.getFPlanFinishDate());
        /*计划产量*/
        sysWorkPlan.setWorkPlanProductNum((long) page.getFauxqty());
        /*机台名称*/
        sysWorkPlan.setMachineName(page.getFHeadSelfJ01100().getFName());
        /*计划开始时间*/
        sysWorkPlan.setActualStartTime(page.getFStartDate());
        /*车间编码*/
        sysWorkPlan.setWorkShopCode(page.getFWorkShop().getFNumber());
        /*车间名称*/
        sysWorkPlan.setWorkShopName(page.getFWorkShop().getFName());
        log.warn("WorkShopName:{}",WorkShopEnum.getEnumByCode(page.getFWorkShop().getFName().substring(0,2)).getName());
        sysWorkPlan.setWorkShopName(WorkShopEnum.getEnumByCode(page.getFWorkShop().getFName().substring(0,2)).getName());
        /*制单时间*/
        sysWorkPlan.setGenerateDateTime(page.getFCheckDate());
        /*结案时间*/
        sysWorkPlan.setCloseDateTime(page.getFCloseDateTime());
        /*工单类型*/
        sysWorkPlan.setWorkPlanType(page.getFWorktypeID().getFName());
        sysWorkPlan.setDistributeManagerId(kingdeeFManagerId);
        sysWorkPlan.setReceiveManagerId(kingdeeSManagerId);
        sysWorkPlan.setUnitId(page.getFUnitID().getFNumber());
        sysWorkPlan.setUnitName(page.getFUnitID().getFName());
        sysWorkPlan.setWorkPlanInterId(String.valueOf(page.getFInterID()));
        /*工单状态*/
        sysWorkPlan.setStatus(page.getFstatus());
        /*产品简称*/
        sysWorkPlan.setProductShortName(page.getFHeadSelfJ01112());
        /*模具编号*/
        if(sysWorkPlan.getWorkShopName().equals(WorkShopEnum.MOLDING_WORK_SHOP.getName())){
            sysWorkPlan.setMoldNo(page.getFHeadSelfJ01107().getFNumber());
        }
        /*制單人*/
        sysWorkPlan.setGenerateUser(page.getFBillerID().getFName());

        /*工单类型*/
        sysWorkPlan.setWorkPlanTypeCode(page.getFType().getFNumber());
        sysWorkPlan.setWorkPlanType(page.getFType().getFName());
        /*生产组*/
        sysWorkPlan.setProductGroup(page.getFWorkShop().getFName());
        sysWorkPlan.setProductGroupCode(page.getFWorkShop().getFNumber());
        /*机种件别*/
        String machineItem=page.getFHeadSelfJ01118();
        sysWorkPlan.setMachineItem(machineItem!=null?machineItem: DefaultEnum.MACHINE_ITEM_OTHER.getName());

        /*客户料号*/
        sysWorkPlan.setCustomerProductId(page.getFHeadSelfJ01111());
        try {
            sysWorkPlan.setQuantity((long) page.getFHeadSelfJ01114().intValue());
        } catch (NullPointerException nullPointerException) {
            sysWorkPlan.setQuantity(0L);
        }

        try {
            sysWorkPlan.setMoldCaveNum((int) Double.parseDouble(page.getFHeadSelfJ01113()));
        } catch (Exception e) {
            sysWorkPlan.setMoldCaveNum(1);
        }

        if (page.getFHeadSelfJ01116() == null) {
            sysWorkPlan.setIsMoldSame(false);
        } else if ("共用".equals(page.getFHeadSelfJ01116())) {
            sysWorkPlan.setIsMoldSame(true);
        }
        if ("小工单切换".equals(page.getFHeadSelfJ01115().getFName())) {
            sysWorkPlan.setExchangeType(ExchangeTypeEnum.NO_AUTO.getCode());
        } else {
            sysWorkPlan.setExchangeType(ExchangeTypeEnum.AUTO.getCode());
        }
        sysWorkPlan.setId(sysWorkPlan.getWorkPlanId());
        log.info("WorkPlan:{}", JSONObject.toJSONString(sysWorkPlan));
        return sysWorkPlan;
    }

    public void getBomChildInfo(BaseWorkPlanSynchronizationVO baseWorkPlanSynchronizationVO) throws IOException {
        String token = getKingdeeToken();
        String url = kingdeeBaseUrl + getBomList + token;
        log.info("URL:{}", url);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        if(StringUtils.isBlank(baseWorkPlanSynchronizationVO.getBillno())) {

            Map<Object, Object> dataMap = MapBuilder.create()
                    .put("Top", baseWorkPlanSynchronizationVO.getSize())
                    .put("PageSize", baseWorkPlanSynchronizationVO.getSize())
                    .put("PageIndex", "1")
                    .put("OrderBy", "[FBillNo] DESC")
                    .put("SelectPage", "1").build();
            if (baseWorkPlanSynchronizationVO.getStatus() != null) {
                dataMap.put("Filter", "[FStatus] =" + baseWorkPlanSynchronizationVO.getStatus());
                //                        .put("Filter","[FStatus] =1")
            }
            Map<Object, Object> map = MapBuilder.create().put("Data", dataMap).build();
            HttpEntity<Map<Object, Object>> httpEntity = new HttpEntity<>(map, headers);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
            log.error("D:{}", responseEntity.getBody());
            JSONObject jsonObject = JSON.parseObject(responseEntity.getBody());
            if (jsonObject.getIntValue("StatusCode") == 200) {
                JSONObject Data = jsonObject.getJSONObject("Data");
                JSONArray jsonArray = Data.getJSONArray("DATA");
                List<BaseBomChildDO> baseBomChildDOList = Lists.newArrayList();
                for (Object object : jsonArray) {
                    String billNo = JSONObject.parseObject(JSONObject.toJSONString(object)).getString("FBillNo");
                    List<BaseBomChildDO> bomChildDOList = getBOMDetail(billNo);
                    baseBomChildDOList.addAll(bomChildDOList);
                }
                if (CollectionUtils.isNotEmpty(baseBomChildDOList)) {
                    baseWorkPlanService.createBaseBomChildBatch(baseBomChildDOList);
                }
            }
        }else{
            String billNo = baseWorkPlanSynchronizationVO.getBillno();
            List<BaseBomChildDO> baseBomChildDOList = getBOMDetail(billNo);
            if(CollectionUtils.isNotEmpty(baseBomChildDOList)){
                baseWorkPlanService.createBaseBomChildBatch(baseBomChildDOList);
            }
        }
    }

    public List<BaseBomChildDO> getBOMDetail(String billNo) throws IOException {
        String token = getKingdeeToken();
        String url = kingdeeBaseUrl + getBomDetail+ token;
        log.info("URL:{}", url);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        Map<Object, Object> map = MapBuilder.create().put("Data",
                MapBuilder.create().put("FBillNo", billNo).build()).build();
        HttpEntity<Map<Object, Object>> httpEntity = new HttpEntity<>(map, headers);
        List<BaseBomChildDO> bomChildList = new ArrayList<>();
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(responseEntity));
        JSONObject body = jsonObject.getJSONObject("body");
        log.info("Body:{}",body.toJSONString());
        if (body.getInteger("StatusCode") == 200) {
            log.error("Json:" + body);
            Bom bom = body.getObject("Data", Bom.class);
            cn.mes.module.mes.utils.kingdee.bom.Page1 page1=bom.getPage1().get(0);
            List<Page2> page2List = bom.getPage2();
            for(Page2 page2 : page2List){
                BaseBomChildDO baseBomChildDO=new BaseBomChildDO();
                baseBomChildDO.setBomId(page1.getFBillNo());
                baseBomChildDO.setId(page2.getFBomDetailID1());
                baseBomChildDO.setStockId(page2.getFStockID1().getFNumber());
                baseBomChildDO.setStockName(page2.getFStockID1().getFName());
                baseBomChildDO.setWorkPlanInterId(String.valueOf(page2.getFICMOInterID1()));
                baseBomChildDO.setUnitId(page2.getFUnitID1().getFNumber());
                baseBomChildDO.setUnitName(page2.getFUnitID1().getFName());
                baseBomChildDO.setMaterialId(page2.getFItemID1().getFNumber());
                baseBomChildDO.setMaterialName(page2.getFItemID1().getFName());
                baseBomChildDO.setEntryId(page2.getFEntryID1());
                baseBomChildDO.setUnitNum(BigDecimal.valueOf(page2.getFQtyScrap1()));
                baseBomChildDO.setStandardNum(BigDecimal.valueOf(page2.getFBOMInPutAuxQTY1()));
                baseBomChildDO.setBomInterId(String.valueOf(page2.getFInterID1()));
                baseBomChildDO.setShouldGetNum(BigDecimal.valueOf(page2.getFAuxQtyPick1()));
                baseBomChildDO.setHasGetNum(BigDecimal.valueOf(page2.getFEntrySelfY0277()));
                baseBomChildDO.setBiller(page1.getFBillerID().getFName());
                baseBomChildDO.setBomDate(page2.getFSendItemDate1().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
                baseBomChildDO.setNote(page2.getFNote1());
                bomChildList.add(baseBomChildDO);
            }

        }

        return bomChildList;
    }



}
